from django.db import models
from django.contrib.auth.base_user import AbstractBaseUser
from django.contrib.auth.models import PermissionsMixin, BaseUserManager
from django.conf import settings


class UserManager(BaseUserManager):
    def _create_user(self, telphone, username, password, **kwargs):
        if not telphone:
            raise ValueError('手机号不能为空')
        user = self.model(telphone=telphone, username=username, **kwargs)
        user.set_password(password)
        user.save()
        return user

    # TODO: 创建普通用户
    def create_user(self, telphone, username, password, **kwargs):
        kwargs['is_superuser'] = False
        return self._create_user(telphone, username, password, **kwargs)

    # TODO: 创建超级用户
    def create_superuser(self, telphone, username, password, **kwargs):
        kwargs['is_superuser'] = True
        return self._create_user(telphone, username, password, **kwargs)


class User(AbstractBaseUser, PermissionsMixin):
    username = models.CharField(max_length=100)
    telphone = models.CharField(max_length=11, unique=True)
    is_active = models.BooleanField(default=True)

    USERNAME_FIELD = 'telphone'
    REQUIRED_FIELDS = []

    objects = UserManager()

    def get_full_name(self):
        return self.username

    def get_short_name(self):
        return self.username


class Article(models.Model):
    title = models.CharField(max_length=100)
    content = models.TextField()
    author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name='articles')

    class Meta:
        # 通过定义模型添加权限
        # (codename, name)
        # codename：表示的是权限的名字
        # name：表示的是这个权限的作用
        permissions = [
            ('view_article', '看文章的权限')
        ]
